const API_BASE_URL = '/api/order-items';

// DOM 元素
const orderItemListSection = document.getElementById('order-item-list');
const createOrderItemSection = document.getElementById('create-order-item');
const editOrderItemSection = document.getElementById('edit-order-item');
const orderItemDetailsSection = document.getElementById('order-item-details');
const orderItemsTableBody = document.querySelector('#order-items-table tbody');
const createOrderItemForm = document.getElementById('create-order-item-form');
const editOrderItemForm = document.getElementById('edit-order-item-form');
const refreshBtn = document.getElementById('refresh-btn');
const editOrderItemBtn = document.getElementById('edit-order-item-btn');
const deleteOrderItemBtn = document.getElementById('delete-order-item-btn');
const backBtn = document.getElementById('back-btn');
const cancelEditBtn = document.getElementById('cancel-edit');

let currentOrderItemId = null;

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 加载订单项列表
    loadOrderItems();
    
    // 导航链接事件监听
    document.querySelector('a[href="index.html"]').addEventListener('click', function(e) {
        e.preventDefault();
        window.location.href = 'index.html';
    });
    
    document.querySelector('a[href="supplier.html"]').addEventListener('click', function(e) {
        e.preventDefault();
        window.location.href = 'supplier.html';
    });
    
    document.querySelector('a[href="product.html"]').addEventListener('click', function(e) {
        e.preventDefault();
        window.location.href = 'product.html';
    });
    
    document.querySelector('a[href="order.html"]').addEventListener('click', function(e) {
        e.preventDefault();
        window.location.href = 'order.html';
    });
    
    document.querySelector('a[href="#order-item-list"]').addEventListener('click', function(e) {
        e.preventDefault();
        showSection(orderItemListSection);
        hideElement(orderItemDetailsSection);
    });
    
    document.querySelector('a[href="#create-order-item"]').addEventListener('click', function(e) {
        e.preventDefault();
        showSection(createOrderItemSection);
        hideElement(orderItemDetailsSection);
    });
    
    // 刷新按钮事件监听
    refreshBtn.addEventListener('click', loadOrderItems);
    
    // 创建订单项表单提交事件监听
    createOrderItemForm.addEventListener('submit', function(e) {
        e.preventDefault();
        createOrderItem();
    });
    
    // 编辑订单项表单提交事件监听
    editOrderItemForm.addEventListener('submit', function(e) {
        e.preventDefault();
        updateOrderItem();
    });
    
    // 详情页面按钮事件监听
    backBtn.addEventListener('click', function() {
        showSection(orderItemListSection);
        hideElement(orderItemDetailsSection);
    });
    
    editOrderItemBtn.addEventListener('click', function() {
        if (currentOrderItemId) {
            showEditForm(currentOrderItemId);
        }
    });
    
    cancelEditBtn.addEventListener('click', function() {
        showSection(orderItemListSection);
        hideElement(editOrderItemSection);
    });
    
    deleteOrderItemBtn.addEventListener('click', function() {
        if (currentOrderItemId && confirm('确定要删除该订单项吗？')) {
            deleteOrderItem(currentOrderItemId);
        }
    });
});

// 显示指定的部分，隐藏其他部分
function showSection(section) {
    orderItemListSection.classList.add('hidden');
    createOrderItemSection.classList.add('hidden');
    editOrderItemSection.classList.add('hidden');
    orderItemDetailsSection.classList.add('hidden');
    
    section.classList.remove('hidden');
}

// 隐藏元素
function hideElement(element) {
    element.classList.add('hidden');
}

// 显示编辑表单
function showEditForm(orderItemId) {
    fetch(`${API_BASE_URL}/${orderItemId}`)
        .then(response => response.json())
        .then(orderItem => {
            // 填充表单数据
            document.getElementById('edit-order-item-id').value = orderItem.id;
            document.getElementById('edit-order-id').value = orderItem.orderID;
            document.getElementById('edit-product-id').value = orderItem.productID;
            document.getElementById('edit-quantity').value = orderItem.quantity;
            document.getElementById('edit-unit-price').value = orderItem.unitPrice;
            
            // 显示编辑表单
            showSection(editOrderItemSection);
        })
        .catch(error => {
            console.error('获取订单项信息失败:', error);
            alert('获取订单项信息失败: ' + error.message);
        });
}

// 更新订单项
function updateOrderItem() {
    const orderItemId = document.getElementById('edit-order-item-id').value;
    const orderItemData = {
        id: orderItemId,
        orderID: parseInt(document.getElementById('edit-order-id').value),
        productID: parseInt(document.getElementById('edit-product-id').value),
        quantity: parseInt(document.getElementById('edit-quantity').value),
        unitPrice: parseFloat(document.getElementById('edit-unit-price').value)
    };

    fetch(`${API_BASE_URL}/${orderItemId}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(orderItemData)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('更新订单项失败');
        }
        return response.json();
    })
    .then(orderItem => {
        alert('订单项更新成功');
        showSection(orderItemListSection);
        loadOrderItems();
    })
    .catch(error => {
        console.error('更新订单项失败:', error);
        alert('更新订单项失败: ' + error.message);
    });
}

// 日期时间格式化
function formatDateTime(dateTime) {
    if (!dateTime) return '';
    const date = new Date(dateTime);
    return date.toLocaleString('zh-CN');
}

// 加载所有订单项
function loadOrderItems() {
    fetch(API_BASE_URL)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(orderItems => {
            renderOrderItemsTable(orderItems);
        })
        .catch(error => {
            console.error('加载订单项失败:', error);
            alert('加载订单项失败: ' + error.message);
            // 使用mock数据
            renderOrderItemsTable(mockOrderItems);
        });
}

// 渲染订单项表格
function renderOrderItemsTable(orderItems) {
    orderItemsTableBody.innerHTML = '';
    
    if (!orderItems || orderItems.length === 0) {
        orderItemsTableBody.innerHTML = '<tr><td colspan="8" style="text-align: center;">暂无订单项数据</td></tr>';
        return;
    }
    
    orderItems.forEach(orderItem => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${orderItem.id}</td>
            <td>${orderItem.orderID}</td>
            <td>${orderItem.productID}</td>
            <td>${orderItem.quantity}</td>
            <td>¥${(orderItem.unitPrice || 0).toFixed(2)}</td>
            <td>¥${(orderItem.subtotal || 0).toFixed(2)}</td>
            <td>${formatDateTime(orderItem.createdTime)}</td>
            <td>
                <button class="btn btn-sm btn-primary view-details-btn" data-id="${orderItem.id}">查看</button>
            </td>
        `;
        orderItemsTableBody.appendChild(row);
    });
    
    // 添加查看详情的事件监听
    document.querySelectorAll('.view-details-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const orderItemId = this.getAttribute('data-id');
            getOrderItemById(orderItemId);
        });
    });
}

// 创建订单项
function createOrderItem() {
    const orderItemData = {
        orderID: parseInt(document.getElementById('order-id').value),
        productID: parseInt(document.getElementById('product-id').value),
        quantity: parseInt(document.getElementById('quantity').value),
        unitPrice: parseFloat(document.getElementById('unit-price').value)
    };

    fetch(API_BASE_URL, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(orderItemData)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('创建订单项失败');
        }
        return response.json();
    })
    .then(orderItem => {
        alert('订单项创建成功');
        createOrderItemForm.reset();
        showSection(orderItemListSection);
        loadOrderItems();
    })
    .catch(error => {
        console.error('创建订单项失败:', error);
        alert('创建订单项失败: ' + error.message);
    });
}

// 根据ID获取订单项
function getOrderItemById(orderItemId) {
    fetch(`${API_BASE_URL}/${orderItemId}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('获取订单项失败');
            }
            return response.json();
        })
        .then(orderItem => {
            displayOrderItemDetails(orderItem);
        })
        .catch(error => {
            console.error('获取订单项失败:', error);
            alert('获取订单项失败: ' + error.message);
        });
}

// 显示订单项详情
function displayOrderItemDetails(orderItem) {
    currentOrderItemId = orderItem.id;
    
    document.getElementById('detail-id').textContent = orderItem.id;
    document.getElementById('detail-order-id').textContent = orderItem.orderID;
    document.getElementById('detail-product-id').textContent = orderItem.productID;
    document.getElementById('detail-quantity').textContent = orderItem.quantity;
    document.getElementById('detail-unit-price').textContent = '¥' + (orderItem.unitPrice || 0).toFixed(2);
    document.getElementById('detail-subtotal').textContent = '¥' + (orderItem.subtotal || 0).toFixed(2);
    document.getElementById('detail-created-time').textContent = formatDateTime(orderItem.createdTime);
    document.getElementById('detail-updated-time').textContent = formatDateTime(orderItem.updatedTime);
    
    showSection(orderItemDetailsSection);
}

// 删除订单项
function deleteOrderItem(orderItemId) {
    fetch(`${API_BASE_URL}/${orderItemId}`, {
        method: 'DELETE'
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('删除订单项失败');
        }
        alert('订单项已删除');
        showSection(orderItemListSection);
        loadOrderItems();
    })
    .catch(error => {
        console.error('删除订单项失败:', error);
        alert('删除订单项失败: ' + error.message);
    });
}

// Mock数据
const mockOrderItems = [
    {
        id: 1,
        orderID: 1,
        productID: 1,
        quantity: 10,
        unitPrice: 2999.00,
        subtotal: 29990.00,
        createdTime: new Date().toISOString(),
        updatedTime: new Date().toISOString()
    },
    {
        id: 2,
        orderID: 2,
        productID: 2,
        quantity: 20,
        unitPrice: 5999.00,
        subtotal: 119980.00,
        createdTime: new Date().toISOString(),
        updatedTime: new Date().toISOString()
    },
    {
        id: 3,
        orderID: 3,
        productID: 3,
        quantity: 20,
        unitPrice: 2499.00,
        subtotal: 49980.00,
        createdTime: new Date().toISOString(),
        updatedTime: new Date().toISOString()
    }
];